package com.alex.seo.service.campaign.executor.publishing;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alex.seo.domain.campaign.Campaign;
import com.alex.seo.domain.campaign.PublishingCampaign;
import com.alex.seo.domain.site.Site;
import com.alex.seo.service.campaign.executor.CampaignExecutionException;
import com.alex.seo.service.campaign.executor.CampaignExecutor;
import com.alex.seo.service.scheduler.SchedulerService;
import com.alex.seo.service.scheduler.SchedulerServiceException;
import com.alex.seo.service.scheduler.dto.JobDTO;

@Transactional(propagation = Propagation.MANDATORY)
public class PublishingCampaignExecutor implements CampaignExecutor<PublishingCampaign> {

	private SchedulerService schedulerService;
	
	@Required
	public void setSchedulerService(SchedulerService schedulerService) {
		this.schedulerService = schedulerService;
	}
	
	@Override
	public void execute(PublishingCampaign campaign) throws CampaignExecutionException {
		try {
			for (Site site : campaign.getSites()) {
				PublishingJobContext context = new PublishingJobContext(campaign.getContentSource(), site);
				JobDTO<PublishingJobContext> jobDTO = JobDTO.<PublishingJobContext>create(PublishingJob.class, campaign.getJobScheduler(), generateJobId(campaign, site))
						.withParam(context);
				schedulerService.schedule(jobDTO);
			}
		} catch (SchedulerServiceException e) {
			throw new CampaignExecutionException(e);
		}
	}

	private String generateJobId(Campaign campaign, Site site) {
		return campaign.getId() + ":" + site.getId();
	}
}
